import type { BugReport } from "../../types/bug";

// API 地址
const BUG_CHECK_API_URL = "/api/bug-check";
const REPO_CHECK_API_URL = "/api/import-github-repo";

/**
 * 新增：解析后端响应的公共辅助函数
 * (同时改进了错误处理)
 */
async function parseReportResponse(res: Response): Promise<BugReport> {
  if (!res.ok) {
    let errorMsg = `后端检测失败: ${res.status} ${res.statusText}`;
    try {
      // 尝试解析后端返回的 JSON 错误信息
      const errData = await res.json();
      if (errData && errData.error) {
        errorMsg = `检测失败：${errData.error}`;
      }
    } catch (e) {
      // 如果响应不是 JSON，则使用原始状态文本
    }
    throw new Error(errorMsg);
  }
  
  const data: {
    results?: Array<{ file: string; issues?: Array<{ line: number; message: string; suggestion?: string }> }>;
    skipped?: string[];
    errors?: string[]; // 处理后端可能返回的错误数组
  } = await res.json();

  // 打印后端处理文件时发生的非致命错误
  if (data.errors && data.errors.length > 0) {
    console.warn("Backend processing errors:", data.errors);
  }

  // 汇总所有文件的 issues
  const issues = (data.results ?? []).flatMap((r) =>
    (r.issues ?? []).map((i) => ({
      file: r.file,
      line: i.line,
      message: i.message,
      suggestion: i.suggestion,
    }))
  );
  
  return {
    issues,
    meta: {
      model: "heuristic", // 暂时硬编码
      enabledFlags: [],
      skipped: data.skipped ?? [],
    },
  };
}

/**
 * 现有函数 (更新为使用 parseReportResponse)
 */
export async function checkBugs(files: File[]): Promise<BugReport> {
  if (!files.length) {
    return { issues: [] };
  }
  const form = new FormData();
  files.forEach((file) => form.append("files", file, file.name));
  
  const res = await fetch(BUG_CHECK_API_URL, {
    method: "POST",
    body: form,
  });

  return parseReportResponse(res);
}

/**
 * 新增：从 GitHub Repo URL 检测
 */
export async function checkBugsFromRepo(url: string): Promise<BugReport> {
  const res = await fetch(REPO_CHECK_API_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ url }),
  });

  return parseReportResponse(res);
}